package com.urea.system.service.impl;

import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.urea.system.domain.*;
import com.urea.system.mapper.TerminalServiceInfoMapper;
import com.urea.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

import static com.urea.system.constants.BusinessConstants.YES;

/**
 * 终端Service业务层处理
 *
 * @author liuzd
 * @date 2023-08-01
 */
@Service
@Slf4j
public class TerminalServiceInfoServiceImpl extends ServiceImpl<TerminalServiceInfoMapper, TerminalServiceInfo> implements ITerminalServiceInfoService {
    @Autowired
    private ITerminalService terminalService;

    @Override
    public void saveTerminalServiceInfo(Long terminalId, Long storeUid, Boolean first, LocalDateTime useExpiredTime) {
        save(new TerminalServiceInfo(terminalId, storeUid, BooleanUtil.toInt(first), useExpiredTime));
    }

    @Override
    public void saveFirstTreminalServiceInfo(Terminal entity) {
        LocalDateTime ueExpiredTime = LocalDateTime.now().plusYears(1);
        if (IterUtil.isEmpty(getTerminalServiceInfos(entity.getId(), entity.getStoreUid(), true))) {
            saveTerminalServiceInfo(entity.getId(), entity.getStoreUid(), true, LocalDateTime.now().plusYears(1));
            entity.setEnable(YES);
            entity.setUseExpiredTime(ueExpiredTime);
            terminalService.saveOrUpdate(entity);
        }
    }

    @Override
    public List<TerminalServiceInfo> getTerminalServiceInfos(Long terminalId, Long storeUid, Boolean first) {
        return lambdaQuery().eq(Objects.nonNull(terminalId), TerminalServiceInfo::getTerminalId, terminalId)
                .eq(Objects.nonNull(storeUid), TerminalServiceInfo::getStoreUid, storeUid)
                .eq(Objects.nonNull(first), TerminalServiceInfo::getFirst, BooleanUtil.toInt(first))
                .orderByDesc(TerminalServiceInfo::getId)
                .list();
    }


}
